package com.example.Arithmetic.Lettcode;

import com.example.Arithmetic.Arithmetic.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 日期：2023/10/14
 * 时间：12:27
 * 描述：后序遍历
 */
public class E04Lettcode145 {


    //    循环遍历
    public List<Integer> preorderTraversal1(TreeNode root) {
        List list = null;
        if (root == null) {
            return list;
        }
        list=new ArrayList();
        TreeNode curr = root;
        LinkedList<TreeNode> linkedList = new LinkedList<>();
        TreeNode p=null;
        while (!linkedList.isEmpty() || curr != null) {
            if (curr != null) {
                linkedList.push(curr);
                curr = curr.left;
            } else {
                TreeNode peek = linkedList.peek();
                if (peek.right==null||peek.right==p){
                    p= linkedList.pop();
                    list.add(p.val);
                }else {
                    curr=peek.right;
                }
            }
        }
        return list;
    }

    //    递归

    public List<Integer> preorderTraversal2(TreeNode root) {
        List list = new ArrayList();
        if (root == null) {
            return list;
        }
        list.add(root.val);
        preorderTraversal2(root.left);
        preorderTraversal2(root.right);
        return list;
    }

    public static void main(String[] args) {
        E04Lettcode145 e04Lettcode144 = new E04Lettcode145();
        TreeNode root = new TreeNode(
                new TreeNode(new TreeNode(4), 2, new TreeNode(7))
                , 1,
                new TreeNode(new TreeNode(5), 3, new TreeNode(6)));
        List<Integer> integerList = e04Lettcode144.preorderTraversal1(root);
        System.out.println(integerList);
    }
}

